package cn.iocoder.yudao.module.member.service.user;

import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserUpdateVo;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserExtendDO;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserExtendMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.math.BigDecimal;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;

/**
 * 会员 User Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Valid
@Slf4j
public class MemberUserServiceExtendImpl implements MemberUserExtendService {

    @Resource
    private MemberUserExtendMapper memberUserExtendMapper;


    @Override
    public MemberUserExtendDO createMemberUserExtend(Long id) {
        MemberUserExtendDO memberUserExtendDO = new MemberUserExtendDO();
        memberUserExtendDO.setUserId(id);
        memberUserExtendDO.setTotalPoint(BigDecimal.ZERO);
        memberUserExtendDO.setTotalDevice(0);
        memberUserExtendDO.setSpendingPower(BigDecimal.ZERO);
        memberUserExtendMapper.insert(memberUserExtendDO);
        return memberUserExtendDO;
    }

    @Override
    @Transactional
    public MemberUserExtendDO updateMemberUserExtend(MemberUserUpdateVo updateReqVO) {
        MemberUserExtendDO user = getUserExtend(updateReqVO.getId());
        user.setTotalPoint(updateReqVO.getTotalPoint());
        user.setTotalDevice(updateReqVO.getTotalDevice());
        log.info("后台手动更新用户扩展信息userId={}",updateReqVO.getId());
        memberUserExtendMapper.updateById(user);
        return user;
    }
    @Override
    public MemberUserExtendDO getUserExtend(Long id) {
        return memberUserExtendMapper.selectByUserId(id);
    }

    @Override
    @Transactional
    public void updateById(MemberUserExtendDO userExtend) {
        log.info("更新用户扩展信息{}", JSONUtil.toJsonStr(userExtend));
        memberUserExtendMapper.updateById(userExtend);
    }

    @Override
    public List<MemberUserExtendDO> selectListByIds(List<Long> userIds) {
        return memberUserExtendMapper.selectList(MemberUserExtendDO::getUserId,userIds);
    }
}
